package org.rui.consumer.proxy;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import org.rui.example.common.model.User;
import org.rui.example.common.service.UserService;
import org.rui.rpc.model.RpcRequest;
import org.rui.rpc.model.RpcResponse;
import org.rui.rpc.serializer.JdkSerializer;

import java.io.IOException;

/**
 * @author: linweirui
 * @date: 2024/12/02 15:58
 */

/**
 * 静态代理,存在consumer端 这个会导致请求每个服务都要写一个静态代理，不方便。
 */
public class UserServiceProxy implements UserService {
    @Override
    public User getUser(User user) {
        JdkSerializer serializer = new JdkSerializer();

        //发送请求
        RpcRequest rpcRequest = RpcRequest.builder()
                .serviceName(UserService.class.getName())
                .methodName("getUser")
                .args(new Object[]{user})
                .parameterTypes(new Class[]{User.class})
                .build();
        try {
            byte[] bodyBytes = serializer.serialize(rpcRequest);
            byte[] result;
            try (HttpResponse httpResponse = HttpRequest.post("http://localhost:8848")
                    .body(bodyBytes)
                    .execute()) {
                result = httpResponse.bodyBytes();
            }
            RpcResponse rpcResponse = serializer.deserialize(result, RpcResponse.class);
            return (User) rpcResponse.getData();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
